from fastapi import APIRouter,Request
from pydantic import BaseModel
from fastapi.templating import Jinja2Templates

class Book(BaseModel):
    b_id:int
    b_name:str
    b_type:str|None = '未知类型'
    msg:str|None = None

api_book = APIRouter()
template = Jinja2Templates(directory='templates')
#查 method:GET http://127.0.0.1:8000/book/1
#删除 method:DELETE http://127.0.0.1:8000/book/1
#增 method:POST http://127.0.0.1:8000/book
#改 method:PUT http://127.0.0.1:8000/book

books = []

@api_book.get(path = '/{id}')
def getBookById(id:int):
    for book in books:
        if book.b_id == id:
            return book

    return "未找到book"
#删除 method:DELETE http://127.0.0.1:8000/book/1
@api_book.delete('/{id}')
def delBookById(id:int):


    return f'删除{id}'

@api_book.post("/")
def addBook(book:Book):
    books.append(book)
    return books
@api_book.put("/")
def modBookById(book:Book):

    return '改'

#finAll
@api_book.get('/')
def findAll(request:Request):
    return template.TemplateResponse(request,name='book_list.html',context={'books':books})
